package com.dhl.cloud.websocket.service;


import java.util.Collection;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhl.cloud.websocket.Connection;
import com.dhl.cloud.websocket.entity.Message;


/**
 * 消息处理服务
 */

@Service
public class MessageService {

    @Autowired
    private RoomService roomService;

    /**
     * 给房间内的所有人发送消息（包括自己）
     */
    public void sendMessageForEveryInRoom(Message message) {
        Set<Connection> room = roomService.queryRoomById(message.getRoomId());
        room.stream().forEach(t->{
            try {
                 t.getSession().getBasicRemote().sendText(JSON.toJSONString(message));
            } catch (Exception e) {
            	e.printStackTrace();
            }
        });
    }


    /**
     * 给房间除自己之外的所有人发送消息
     */
    public void sendMessageForEveryExcludeSelfInRoom(Message message) {
        Set<Connection> room = roomService.queryRoomById(message.getRoomId());
        room.stream().forEach(t->{
            try {
                if (!message.getUsername().equals(t.getUsername())) {
                     t.getSession().getBasicRemote().sendText(JSON.toJSONString(message));
                }
            } catch (Exception e) {
            	e.printStackTrace();
            }
        });
    }


    /**
     * 给在线的所有人发送消息（包括自己）
     */
    public void sendMessageForAllOnline(Message message) {
        Collection<Set<Connection>> rooms = roomService.queryAllRoom();
        rooms.stream().forEach(t-> t.stream().forEach(k->{
            try {
                k.getSession().getBasicRemote().sendText(JSON.toJSONString(message));
            } catch (Exception e) {
            	e.printStackTrace();
            }
        }));
    }


    public void sendMessageToTarget(Message message) {
        // 获取目标用户的连接
        Connection targetConnection = roomService.getConnectionInRoom(message.getRoomId(), message.getTarget());
        if (targetConnection != null && targetConnection.getSession().isOpen()) {
            try {
                targetConnection.getSession().getBasicRemote()
                        .sendText(JSON.toJSONString(message));
            } catch (Exception e) {
                // 处理发送失败情况
                e.printStackTrace();
            }
        }
    }
}
